import json
import os
import requests
from urllib.parse import quote
from concurrent.futures import ThreadPoolExecutor, as_completed


# 读取api_data.json文件
with open('api_data.json', 'r') as file:
    data = json.load(file)

# 定义视频质量优先级
quality_priority = ['FHD', 'HD', 'LD', 'SD']

# 创建保存视频的目录
output_dir = "./videos1"
if not os.path.exists(output_dir):
    os.makedirs(output_dir)

data = data['data']['data']

video_urls = []

# 遍历章节
for chapter in data:
    chapter_title = chapter['title']
    playlist = chapter['resource']["data"]["playlist"]  
    if playlist is None:
        continue
    
    # 遍历播放列表中的视频
    for q, video in playlist.items():
        video_url = video.get('url')
        video_urls.append({
            "title": chapter_title,
            "url": video_url
        })
        break


# 下载函数
def download_video(index, video):
    """下载单个视频"""
    filename = f"{video['title']}.mp4"
    video_url = video["url"]
    output_file = os.path.join(output_dir, filename)

    try:
        print(f"正在下载视频 {index}: {filename}")
        response = requests.get(video_url, stream=True)
        response.raise_for_status()  # 检查请求是否成功

        # 保存到文件
        with open(output_file, "wb") as file:
            for chunk in response.iter_content(chunk_size=8192):
                file.write(chunk)
        print(f"视频 {index} 已成功保存为 {output_file}")
    except requests.exceptions.RequestException as e:
        print(f"视频 {index} 下载失败: {e}")

# 使用多线程下载
def download_videos_multithreaded(video_urls):
    """多线程批量下载视频"""
    with ThreadPoolExecutor(max_workers=10) as executor:  # 设置线程池最大线程数
        futures = {
            executor.submit(download_video, index + 1, url): url
            for index, url in enumerate(video_urls)
        }
        for future in as_completed(futures):
            try:
                future.result()  # 获取线程执行结果
            except Exception as e:
                print(f"线程执行出错: {e}")

# 开始多线程下载
download_videos_multithreaded(video_urls)

print("All videos downloaded.")